package com.cy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@EnableFeignClients
@SpringBootApplication
public class ScaConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScaConsumerApplication.class, args);
    }
    //springboot 工程中可以用此对象（resttemplate）调用第三方的服务
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Bean
    @LoadBalanced
    public  RestTemplate loadBalancedRestTemplate(){
        return new RestTemplate();
    }
    @RestController
     public class ConsumerController{
        @Value("${spring.application.name}")
        private String consumerName;
        @Autowired
        private RestTemplate restTemplate;

        @GetMapping("/consumer/dorestecho01")
        public String doEcho(){
           String url = "http://localhost:8081/provider/echo/"+consumerName;
            return restTemplate.getForObject(url, String.class);

        }
        @Autowired
        private LoadBalancerClient loadBalancerClient;
        @GetMapping("/consumer/dorestecho02")
        public String doEcho2(){
            ServiceInstance choose = loadBalancerClient.choose("sca-provider");
            String host = choose.getHost();
            int port = choose.getPort();
            String url = "http://"+host+":"+port+"/provider/echo/"+consumerName;
            return restTemplate.getForObject(url, String.class);

        }

    }
}
